package com.alibaba.citrus.ots.sales.plan.facade.service.statistics.stat.customer;

import com.alibaba.citrus.ots.common.util.SpringContextUtil;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.MonthContractAndRollingCountResponse;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.QueryContractByCustomerDimensionRequest;
import com.alibaba.citrus.ots.sales.plan.facade.service.statistics.stat.SalesPlanStatAtomAbstract;
import com.alibaba.citrus.ots.sales.plan.facade.service.statistics.stat.model.SalesPlanStatRequest;
import com.alibaba.citrus.ots.sales.plan.model.enums.ContractDataSourceEnum;
import com.alibaba.citrus.ots.sales.plan.model.enums.ContractStatDimensionEnum;
import com.alibaba.citrus.ots.sales.plan.repository.SalesPlanCustomerStatRepository;
import com.alibaba.citrus.ots.sales.plan.repository.request.StatCustomerQueryRequest;
import com.alibaba.citrus.ots.sales.plan.sdo.SalesPlanSDO;
import com.alibaba.citrus.ots.sales.plan.sdo.SalesPlanStatCustomerSDO;
import com.alibaba.cz.base.tool.log.Log;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

/**
 * @author luyi
 * @date 2021/12/2 10:38 上午
 */
public class CustomerStatService extends SalesPlanStatAtomAbstract {

    private static final Log log = Log.getLogger(CustomerStatService.class);

    /**
     * 汇总哪些状态的明细
     */
    private List<Integer> statusList;

    private final static SalesPlanCustomerStatRepository salesPlanCustomerStatRepository;
    static {
        salesPlanCustomerStatRepository = SpringContextUtil.getBean(SalesPlanCustomerStatRepository.class);
    }

    public CustomerStatService(SalesPlanStatRequest statRequest,CountDownLatch latch){
        super.statRequest = statRequest;
        super.latch = latch;
    }

    public CustomerStatService(SalesPlanStatRequest statRequest,List<Integer> statusList){
        super.statRequest = statRequest;
        this.statusList = statusList;
    }

    @Override
    protected void handle(SalesPlanStatRequest statRequest) {
        planCustomerCollect(statRequest.getSalesPlan(),statRequest.getYear(),statRequest.getMonth());
    }

    @Override
    protected String taskName() {
        return "CustomerStatService.gather";
    }

    /**
     * 客户维度汇总
     *
     * @param salesPlan
     */
    private void planCustomerCollect(SalesPlanSDO salesPlan, String year, String month) {
        //获取有多少客户地址
        log.info("SalesPlanStatServiceImpl.planCustomerCollect.start");
        Integer addressCount = salesPlanLineRepository.queryPlanCustomerCount(salesPlan.getId().toString(),statusList);
        if (addressCount == null || addressCount <= 0) {
            log.warn("SalesPlanStatServiceImpl.planCustomerCollect planCustomerAddress nothingness");
            return;
        }
        int totalPage = (addressCount + CUSTOMER_ADDRESS_PAGE_SIZE - 1) / CUSTOMER_ADDRESS_PAGE_SIZE;
        for (int i = 1; i <= totalPage; i++) {
            StatCustomerQueryRequest statQueryRequest = new StatCustomerQueryRequest();
            statQueryRequest.setPlanId(salesPlan.getId().toString());
            statQueryRequest.setSize(CUSTOMER_ADDRESS_PAGE_SIZE);
            statQueryRequest.setPage(i);
            if (CollectionUtils.isNotEmpty(statusList)){
                statQueryRequest.setStatusList(statusList);
            }
            List<SalesPlanStatCustomerSDO> salesPlanStatCustomerList = salesPlanLineRepository.queryStatPlanCustomerList(statQueryRequest);
            if (CollectionUtils.isEmpty(salesPlanStatCustomerList)) {
                log.warn("SalesPlanStatServiceImpl.planCustomerCollect.salesPlanStatCustomerList nothingness");
                break;
            }
            // 批量查询客户地址合同量，合同金额
            List<String> customerAddressIdList = salesPlanStatCustomerList.stream().map(SalesPlanStatCustomerSDO::getCustomerAddressId).collect(Collectors.toList());

            QueryContractByCustomerDimensionRequest queryContractRequest = new QueryContractByCustomerDimensionRequest();
            queryContractRequest.setType(ContractStatDimensionEnum.CUSTOMER.getCode());
            queryContractRequest.setCustomerAddressesIds(customerAddressIdList);
            queryContractRequest.setContractYear(year);
            queryContractRequest.setPlanMonth(month);
            queryContractRequest.setDataSource(ContractDataSourceEnum.CUSTOMER.getCode());
            List<MonthContractAndRollingCountResponse> monthContractAndRollingCountResponses = contractRepository.queryQuantityListByAddressAndScItem(queryContractRequest);
            Map<String, MonthContractAndRollingCountResponse> collect = Maps.newHashMap();
            if (CollectionUtils.isNotEmpty(monthContractAndRollingCountResponses)) {
                collect = monthContractAndRollingCountResponses.stream().collect(Collectors.toMap(MonthContractAndRollingCountResponse::getCustomerAddressId, a -> a, (a, b) -> a));
            }
            // 计算合同满意度 计划状态不同 计算满意度方式不同
            for (SalesPlanStatCustomerSDO planStatCustomer : salesPlanStatCustomerList) {
                // 查合同量补充
                MonthContractAndRollingCountResponse monthContract = collect.get(planStatCustomer.getCustomerAddressId());
                setStatContractInfo(planStatCustomer, monthContract);
                calculateSatisfaction(salesPlan.getStatus(), planStatCustomer);
            }
            boolean result = salesPlanCustomerStatRepository.batchCreatePlanCustomer(salesPlanStatCustomerList);
            log.info("客户汇总数据插入返回结果:{}", result);
        }
        log.info("SalesPlanStatServiceImpl.planCustomerCollect.end");
    }
}
